<?php
class SiteController extends Zend_Controller_Action
{

	public function init()
	{
		// Set lang to view
		$this->view->lang = $this->_request->getParam ( 'lang', 'en' );
		$this->view->action = $this->getRequest()->getActionName();
	}

	public function homeAction() {
		$productModel = new Model_Product();
    	$this->view->productList = $productModel->getList('status = 1')->toArray();    	
	}

	public function loginAction()
	{
		$postData = $this->_request->getPost();
	
		if($this->_request->isPost() && isset($postData ['username']) && isset($postData ['password']))
		{
			if($postData ['username'] == "" || $postData ['password'] == "") {
				$this->view->loginMessage = "loi";
			} else {
				//set up the auth adapter
				//get the default db adapter
				$db = Zend_Db_Table::getDefaultAdapter ();
				
				//create the auth adapter
				$authAdapter = new Zend_Auth_Adapter_DbTable ( $db, 'members', 'username', 'password' );
				
				//set the username and password
				$authAdapter->setIdentity ( $postData ['username'] );
				$authAdapter->setCredential ( md5 ( $postData ['password'] ) );
				
				//authenticate
				$result = $authAdapter->authenticate ();
				if ($result->isValid ()) {
					// store the username, first and last names of the user
					$auth = Zend_Auth::getInstance ();
					$storage = $auth->getStorage ();
					$object = $authAdapter->getResultRowObject ( array ('id', 'email', 'username'));
					$object->role = 'member';
				
					$storage->write ( $object );
					return $this->_redirect ( 'site/home' );
				} else {
					$this->view->loginMessage = "Sorry, your username or password was incorrect";
				}
			}
		}
		return $this->render ( 'login' );
	}
	
	public function logoutAction()
	{
		$authAdapter = Zend_Auth::getInstance ();
		$authAdapter->clearIdentity ();
	
		return $this->_redirect ( 'site/home' );
	}
	
	public function forgotpasswordAction() {
		// Set no error
		$this->view->error = 0;
		
		if($this->_request->isPost())
		{
			$postData = $this->_request->getPost();
			foreach($postData as &$param) {
				$param = stripslashes(trim($param));
			}
		
			// Create user model
			$usrModel = new Model_Member();
				
			if( $usrModel->numRows(array('email = ?'=>$postData['email'])) == 0 )
			{
				$this->view->error = 1;
			} else {
				// generate new password
				$newpass = '';
				for($i = 0; $i<=10 ;$i++)
				{
					$newpass .= rand ( 0, 9 );
				}
				
				$mail = new CMS_Mail();
				$mail->setTemplate('forgotpassword');
				$mail->newpass = $newpass;
				
				$mail->setRecipient($postData['email']);
				$mail->send();
				
				// update password
				$user = $usrModel->getUserByEmail($postData['email']);
				$usrModel->updatePassword($user['id'], $newpass);
				
				$this->render ( "forgotpassword-successfully" );
			}
		}
	}
	
	public function contactAction() {
		$frmContact = new Form_Site_Contact ( );
		if ($this->_request->isPost ())
		{
			// get the posted data
			$sender = $this->_request->getParam ( 'name' );
			$email = $this->_request->getParam ( 'email' );
			$subject = $this->_request->getParam ( 'title' );
			$message = $this->_request->getParam ( 'message' );
		
			$mail = new CMS_Mail();
			$mail->setTemplate('contact');
			$mail->sender = $sender;
			$mail->email = $email;
			$mail->subject = $subject;
			$mail->message = $message;
		
			$mail->setRecipient('chungkhanhduy1985@gmail.com');
			$mail->send();
		
			// inform the view with the status
			$this->view->messageProcessed = true;
		}
		$frmContact->setAction ( $this->_helper->url ( 'contact', 'site' ) );
		$this->view->form = $frmContact;
	}

	public function productAction() {
		$filter = array('status = ?' => 1);
		
		$catID = $this->_request->getParam ( 'cat_id' );
		if($catID){
			$filter['cat_id = ?'] = $catID;
		}
		
		$dimID = $this->_request->getParam ( 'dim_id' );
		if($dimID){
			$filter['dim_id = ?'] = $dimID;
		}
		
		$productModel = new Model_Product();
    	$this->view->productList = $productModel->getList($filter)->toArray();    	
	}

	
	public function registrationAction() {
		// Set no error
		$this->view->error = 0;
		
		if($this->_request->isPost())
		{
			$postData = $this->_request->getPost();
			foreach($postData as &$param) {
				$param = stripslashes(trim($param));
			}
		
			// Create user model
			$usrModel = new Model_Member();
		
			if( $usrModel->numRows(array('username = ?'=>$postData['username'])) || !$postData['username'])
			{
				$this->view->error = 1;
			}
			elseif ( $usrModel->numRows(array('email = ?'=>$postData['email'])) || !$postData['email'])
			{
				$this->view->error = 2;
			}
			else
			{
				$user = $usrModel->fetchNew();
				$user->username = $postData['username'];
				$user->password = md5($postData['password']);
				$user->fullname = $postData['fullname'];
				$user->email = $postData['email'];
				//$user->active = 1;
		
				$dateObject = Zend_Date::now ();
				$user->created_ts = $dateObject->toString("YYYY-MM-dd HH:mm:ss");
				$user->save();
		
				$this->render ( "registration-successfully" );
			}
		}
	}

	public function productDetailAction() {
		$productID = $this->_request->getParam ( 'product_id' );
		  
		$mdlProduct = new Model_Product();
		$p = $mdlProduct->find ( $productID )->current();
		
		$this->view->currentProduct = $p;			
		
		$imageModel = new Model_Image();
    	$this->view->imageList = $imageModel->getList('product_id = ' . $p['product_id'] )->toArray();    
	}

	public function searchAction()
	{
		$key = $this->_request->getParam ( 'txtSearch' );
		$priceFrom = $this->_request->getParam ( 'price_from' );
		$priceTo = $this->_request->getParam ( 'price_to' );
		
		$filters = array();
		if($key)
		{
			$filters["name like ?"] = "%".$key."%";
		}
		if($priceFrom)
		{
			$filters["price >= ?"] = $priceFrom;
		}
		if($priceTo)
		{
			$filters["price <= ?"] = $priceTo;
		}
		
		$this->view->key = $key;
		$this->view->priceFrom = $priceFrom;
		$this->view->priceTo = $priceTo;
		
		
		$mdlProduct = new Model_Product();
		$this->view->productList = $mdlProduct->getList($filters)->toArray();   
	}

}